package com.fqgj.xjd.user.service;

import com.fqgj.common.utils.StringUtils;
import com.fqgj.xjd.user.dao.UserAccessDao;
import com.fqgj.xjd.user.entity.UserAccessEntity;
import com.fqgj.xjd.user.so.UserAccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName:
 * @Description: 用户登录服务
 * @Author zhangxingyun
 * @Create 2017-07-21 09:37
 */
@Service
public class UserAccessService {
    @Autowired
    UserAccessDao userAccessDao;

    @Autowired
    UserRegistService userRegistService;

    /**
     * 更新登录token
     * @param userCode
     * @return
     */
    public UserAccessToken refreshUserAccessToken(String userCode) {
        UserAccessEntity userAccessEntity = userAccessDao.selectUserAccessByUserCode(userCode);
        UserAccessToken userAccessToken = new UserAccessToken(userCode);
        userAccessEntity.setToken(userAccessToken.getToken());
        userAccessEntity.setExpireDate(userAccessToken.getExpireDate());
        userAccessDao.updateByPrimaryKey(userAccessEntity);

        return userAccessToken;
    }


    /**
     * 判断是否设置密码
     * @param userCode
     * @return
     */
    public boolean isUserPasswordSetted(String userCode) {
        UserAccessEntity userAccessEntity = userAccessDao.selectUserAccessByUserCode(userCode);
        return userAccessEntity != null && StringUtils.isNotEmpty(userAccessEntity.getPassWord());
    }


    /**
     * 更新密码
     * @param userCode
     * @param passWord
     */
    public void updateUserPassword(String userCode, String passWord) {
        UserAccessEntity userAccessEntity = userAccessDao.selectUserAccessByUserCode(userCode);
        userAccessEntity.setPassWord(passWord);
        userAccessDao.updateByPrimaryKey(userAccessEntity);
    }


    /**
     * 迁移token 是新的token对应旧的用户
     * @param oldUser
     * @param newUser
     */
    public void moveTokenToOldUser(UserAccessEntity oldUser, UserAccessEntity newUser) {
        oldUser.setToken(newUser.getToken());
        oldUser.setExpireDate(newUser.getExpireDate());
        userAccessDao.updateByPrimaryKey(oldUser);

        //更改此token 使token只对应旧用户
        newUser.setToken("");
        newUser.setMobile(null);
        newUser.setDeleted(true);
        userAccessDao.updateByPrimaryKey(newUser);
    }
}
